<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <!-- 插入到left插槽位置 -->
        <template #left>
          <span>本月: 社保在缴 公积金在缴</span>
        </template>
        <!-- 插入到right插槽位置 -->
        <template #right>
          <el-button type="warning" size="small" @click="hImport">导入excel</el-button>
          <el-button type="danger" size="small" @click="handleDownload">导出excel</el-button>
          <el-button type="primary" size="small" @click="hAdd">新增员工</el-button>
        </template>
      </page-tools>
      <el-table
        :data="list"
        style="width: 100%"
        :default-sort="{prop: 'timeOfEntry', order: 'descending'}"
      >
        <el-table-column
          label="序号"
          type="index"
          :index="indexMethod"
        />
        <el-table-column
          label="姓名"
          prop="username"
        />
        <el-table-column
          label="手机号"
          prop="mobile"
        />
        <el-table-column
          label="图片"
          prop="username"
        >
          <template slot-scope="scope">
            <!-- <img :src="scope.row.staffPhoto" alt="" style="width:80px"> -->
            <ImageHolder :src="scope.row.staffPhoto" />
          </template>
        </el-table-column>
        <el-table-column
          label="工号"
          prop="workNumber"
        />
        <el-table-column
          label="聘用形式"
          prop="formOfEmployment"
        >
          <template slot-scope="scope">
            <!-- {{scope}}报错，定义方法在下面打印看scope结构 -->
            <!-- {{ scope.row.formOfEmployment===1?'正式':'非正式' }} -->
            {{ format(scope.row.formOfEmployment) }}
          </template>
        </el-table-column>
        <el-table-column
          label="部门"
          prop="departmentName"
        />
        <el-table-column
          label="入职时间"
          prop="timeOfEntry"
          sortable
        />
        <el-table-column
          label="操作"
          width="280"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="$router.push('/employees/detail?id='+scope.row.id)"
            >查看</el-button>
            <el-button
              size="mini"
              type="text"
              @click="hRole(scope.row.id)"
            >分配角色</el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="currentPage"
        :page-sizes="[2, 3 , 5, 10]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <el-dialog title="新增员工" :visible.sync="showDialog">
        <empDialog v-if="showDialog" @success="hSuccess" />
      </el-dialog></div>
    <!-- Role分配权限 -->
    <el-dialog :visible.sync="showRole" title="分配角色">
      <assignRole v-if="showRole" :employee-id="employeeId" :show-role.sync="showRole" @closeDialog="closeRole" />
    </el-dialog>
  </div>
</template>
<script>
// import pageTools from '@/components/pageTools'
// export default {
//   components: {
//     pageTools
//   }
// }
import { getEmployeesList, delEmployees } from '@/api/employees'
import employeeENUM from '@/constant/employees.js'
import empDialog from './empDialog.vue'
import assignRole from './assignRole.vue'
// console.log(employeeENUM.hireType)
const map = employeeENUM.hireType.reduce((acc, cur) => {
  // console.log(acc, cur)
  acc[cur.id] = cur.value
  return acc
}, {})
// console.log('map', map)
export default {
  components: { empDialog, assignRole },
  data() {
    return {
      list: [],
      // indexMethod: 1,
      currentPage: 1,
      pageSize: 2,
      total: 0,
      showDialog: false,
      tHeader: [],
      showRole: false,
      employeeId: ''
    }
  },
  async created() {
    // this.fn()
    this.loadEmployeesList()
  },
  methods: {
    closeRole() {
      this.showRole = false
    },
    hRole(id) {
      this.showRole = true
      this.employeeId = id
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(async(excel) => {
        // 导出所有数据改list值
        const res = await getEmployeesList(this.currentPage, this.total)
        // console.log(res)
        // const list = this.list
        const list = res.data.rows // 拿不到数据可以拿到import外，让异步操作
        const data = this.formatJson(list)
        // const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date', 'Id', 'Title', 'Author', 'Readings', 'Date']
        const tHeader = this.tHeader
        // console.log(list, 22222)
        excel.export_json_to_excel({
          header: tHeader,
          // data: [
          //   ['张三', '男'],
          //   ['李四', '男'],
          //   ['王五', '女']
          // ],
          data,
          // filename: this.filename,
          filename: '前端87',
          // autoWidth: this.autoWidth,
          autoWidth: false,
          bookType: this.bookType
          // bookType: 'txt'
        })
        this.downloadLoading = false
      })
    },
    formatJson(list) {
      /* 目的：得到一个二维数组并返回 */
      // console.log(list, 9999)
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 处理tHeader
      this.tHeader = Object.values(map)
      return list.map(item => { // 函数返回值
        // 获取需要的key
        return Object.keys(map).map(key => { // 二维数组.map是因为需要返回值
          // 根据key获值
          return item[key] // 小数组
        })
      })
      // return list
    },
    hImport() {
      this.$router.push('/import')
    },
    hSuccess() {
      this.showDialog = false
      // 页面跳转
      this.total++
      this.currentPage = Math.ceil(this.total / this.pageSize)
      this.loadEmployeesList()
    },
    format(id) {
      // const item = employeeENUM.hireType.find(item => item.id === id)
      // if (item) {
      //   return item.value
      // } else {
      //   return '未知'
      // }
      return map[id]
    },
    hAdd(index, row) {
      this.showDialog = true
    },
    handleDelete(index, row) {
      // console.log(index, row)
      const id = row.id
      this.hDel(id)
      // delRole(id)
    },
    doDel(id) {
      delEmployees(id)
      if (this.roles.length === 1) {
        this.currentPage--
        if (this.currentPage === 0) {
          this.currentPage = 1
        }
      }
      this.loadEmployeesList()
      this.$message.success('删除成功')
    },
    hDel(id) {
      this.$confirm('你确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doDel(id)
      }).catch(() => {
        // 用户取消退出
      })
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.currentPage = 1
      this.pageSize = val
      this.loadEmployeesList(this.currentPage, this.pageSize)
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      // console.log(val)
      this.currentPage = val
      this.loadEmployeesList(this.currentPage, this.pageSize)
    },
    async loadEmployeesList() {
      const res = await getEmployeesList(this.currentPage, this.pageSize)
      // console.log(res.data.rows)
      this.list = res.data.rows
      this.total = res.data.total
    },
    indexMethod(index) {
      // console.log(row, '123123')
      // return row
      const val = this.currentPage * this.pageSize + index - 1
      // console.log(val)
      return val
    }
    // handleEdit() {}

  }
}
</script>
